package com.qdhh.enrollment.controller.miniapp;

import cn.dev33.satoken.stp.StpUtil;
import com.qdhh.enrollment.common.Result;
import com.qdhh.enrollment.model.Registration;
import com.qdhh.enrollment.service.RegistrationService;
import com.qdhh.enrollment.service.StudentService;
import com.qdhh.enrollment.service.dto.LoginResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "小程序-用户认证", description = "小程序用户登录、注册、个人信息管理接口")
@RestController
@RequestMapping("/api/miniapp/user")
@Validated
public class MiniappUserController {

    private final StudentService studentService;
    private final RegistrationService registrationService;

    public MiniappUserController(StudentService studentService, RegistrationService registrationService) {
        this.studentService = studentService;
        this.registrationService = registrationService;
    }

    @Operation(summary = "微信登录", description = "通过微信授权码登录，返回学生信息和Token")
    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<Map<String, Object>> login(
            @Parameter(description = "微信授权码（GET请求参数）") @RequestParam(value = "code", required = false) String codeParam,
            @Parameter(description = "登录请求体（POST请求）") @RequestBody(required = false) LoginRequest requestBody) {
        String code = StringUtils.hasText(codeParam) ? codeParam : (requestBody != null ? requestBody.getCode() : null);
        if (!StringUtils.hasText(code)) {
            return Result.failure(400, "code不能为空");
        }
        String nickName = requestBody != null ? requestBody.getNickName() : null;
        String avatarUrl = requestBody != null ? requestBody.getAvatarUrl() : null;
        String unionId = requestBody != null ? requestBody.getUnionId() : null;
        LoginResult loginResult = studentService.login(code, nickName, avatarUrl, unionId);
        Map<String, Object> payload = new HashMap<>();
        payload.put("student", loginResult.getUser());
        payload.put("token", loginResult.getToken());
        return Result.success("OK", payload);
    }

    @Operation(summary = "更新手机号", description = "更新当前登录用户的手机号，需要登录认证")
    @PutMapping("/phone")
    public Result<Void> updatePhone(@RequestBody PhoneRequest request) {
        String studentId = StpUtil.getLoginIdAsString();
        String phone = request != null ? request.getPhone() : null;
        studentService.updatePhone(studentId, phone);
        return Result.success("OK", null);
    }

    @Operation(summary = "更新学号", description = "更新当前登录用户的学号，并触发身份认证，需要登录认证")
    @PutMapping("/studentNo")
    public Result<Void> updateStudentNo(@RequestBody StudentNoRequest request) {
        String studentId = StpUtil.getLoginIdAsString();
        String studentNo = request != null ? request.getStudentNo() : null;
        studentService.updateStudentNo(studentId, studentNo);
        return Result.success("OK", null);
    }

    @Operation(summary = "注册", description = "提交注册信息（用于预注册），不需要登录认证")
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterRequest request) {
        if (request == null
            || !StringUtils.hasText(request.getName())
            || !StringUtils.hasText(request.getStudentId())
            || !StringUtils.hasText(request.getMajor())
            || !StringUtils.hasText(request.getClassName())
            || !StringUtils.hasText(request.getPhone())
            || !StringUtils.hasText(request.getEmail())) {
            return Result.failure(400, "注册信息不完整");
        }

        LocalDateTime now = LocalDateTime.now();
        Registration registration = Registration.builder()
            .name(request.getName())
            .studentId(request.getStudentId())
            .major(request.getMajor())
            .className(request.getClassName())
            .phone(request.getPhone())
            .email(request.getEmail())
            .createdAt(now)
            .updatedAt(now)
            .build();

        registrationService.save(registration);
        return Result.success("OK", "REGISTERED");
    }

    public static class LoginRequest {
        private String code;
        private String nickName;
        private String avatarUrl;
        private String unionId;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getNickName() {
            return nickName;
        }

        public void setNickName(String nickName) {
            this.nickName = nickName;
        }

        public String getAvatarUrl() {
            return avatarUrl;
        }

        public void setAvatarUrl(String avatarUrl) {
            this.avatarUrl = avatarUrl;
        }

        public String getUnionId() {
            return unionId;
        }

        public void setUnionId(String unionId) {
            this.unionId = unionId;
        }
    }

    public static class PhoneRequest {
        private String phone;

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }
    }

    public static class StudentNoRequest {
        private String studentNo;

        public String getStudentNo() {
            return studentNo;
        }

        public void setStudentNo(String studentNo) {
            this.studentNo = studentNo;
        }
    }

    public static class RegisterRequest {
        private String name;
        private String studentId;
        private String major;
        private String className;
        private String phone;
        private String email;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getStudentId() {
            return studentId;
        }

        public void setStudentId(String studentId) {
            this.studentId = studentId;
        }

        public String getMajor() {
            return major;
        }

        public void setMajor(String major) {
            this.major = major;
        }

        public String getClassName() {
            return className;
        }

        public void setClassName(String className) {
            this.className = className;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }
}

